class PPGFatigueCalculator {
    constructor(sampleRate = 250) {
        this.sampleRate = sampleRate; // 采样率 (Hz)
        this.windowSize = 10 * sampleRate; // 10秒的数据点数 (2500)
        this.ppgBuffer = []; // PPG数据缓冲区
        this.filteredBuffer = []; // 滤波后数据缓冲区
        
        // IIR带通滤波器参数 (0.5-5Hz, 250Hz采样率)
        this.b = [0.0082, 0, -0.0164, 0, 0.0082]; // 分子系数
        this.a = [1, -3.764, 5.326, -3.372, 0.803]; // 分母系数
        this.x = new Array(5).fill(0); // 输入历史
        this.y = new Array(5).fill(0); // 输出历史
    }

    // IIR滤波处理
    iirFilter(signal) {
        let output = 0;
        this.x.unshift(signal);
        this.x.pop();
        
        for (let i = 0; i < this.b.length; i++) {
            output += this.b[i] * this.x[i];
        }
        for (let i = 1; i < this.a.length; i++) {
            output -= this.a[i] * this.y[i-1];
        }
        
        this.y.unshift(output);
        this.y.pop();
        return output;
    }

    // 计算心率变异性 (HRV) 的 RMSSD
    calculateRMSSD(peaks) {
        if (peaks.length < 2) return 0;
        let rrIntervals = [];
        for (let i = 1; i < peaks.length; i++) {
            rrIntervals.push((peaks[i] - peaks[i-1]) / this.sampleRate * 1000); // ms
        }
        let squaredDiffs = [];
        for (let i = 1; i < rrIntervals.length; i++) {
            squaredDiffs.push(Math.pow(rrIntervals[i] - rrIntervals[i-1], 2));
        }
        return Math.sqrt(squaredDiffs.reduce((a, b) => a + b, 0) / squaredDiffs.length);
    }

    // 检测峰值
    detectPeaks(signal) {
        let peaks = [];
        for (let i = 1; i < signal.length - 1; i++) {
            if (signal[i] > signal[i-1] && signal[i] > signal[i+1] && signal[i] > 0) {
                peaks.push(i);
            }
        }
        return peaks;
    }

    // 计算疲劳度
    calculateFatigue() {
        if (this.filteredBuffer.length < this.windowSize) {
            return -1;
        }

        // 检测峰值
        const peaks = this.detectPeaks(this.filteredBuffer);
        
        // 计算HRV (RMSSD)
        const rmssd = this.calculateRMSSD(peaks);
        
        // 计算平均心率
        const heartRate = peaks.length / 10 * 60; // 每分钟心跳次数
        console.log('平均心率'+heartRate)
        
        // 疲劳度评分 (基于HRV和心率)
        let fatigueScore = 0;
        if (rmssd > 0) {
            // RMSSD通常在20-100ms，较低值表示更高疲劳
            fatigueScore += Math.min(100, (100 - rmssd) * 0.8);
        }
        if (heartRate > 0) {
            // 心率高于100bpm可能表示疲劳
            fatigueScore += Math.min(100, Math.max(0, heartRate - 80) * 0.5);
        }
        
        // 限制范围在0-100
        fatigueScore = Math.min(100, Math.max(0, fatigueScore));
        // console.log(fatigueScore)
        
        // 清空缓冲区
        this.ppgBuffer = [];
        this.filteredBuffer = [];
        
        return Math.round(fatigueScore);
    }

    // 处理新的PPG数据点
    processPPG(dataPoint, heartPoint) {
        this.ppgBuffer.push(dataPoint);
        
        // 应用IIR滤波
        const filteredPoint = this.iirFilter(dataPoint);
        this.filteredBuffer.push(filteredPoint);
        
        let fatigueScore1 = 0;
        if (heartPoint > 0) {
            // 心率高于100bpm可能表示疲劳
            fatigueScore1 += Math.min(100, Math.max(0, heartPoint - 40) * 0.5);
        }
        
        // 限制范围在0-100
        fatigueScore1 = Math.min(100, Math.max(0, fatigueScore1));
        // console.log(fatigueScore)
        

        return Math.round(fatigueScore1);

        // // 检查是否满足10秒数据
        // if (this.ppgBuffer.length >= this.windowSize) {
        //     return this.calculateFatigue();
        // }
        // return -1;
    }
}

export { PPGFatigueCalculator };

// // 生成模拟PPG信号
// function generatePPGSignal(sampleRate, durationSeconds) {
//     const samples = Math.floor(sampleRate * durationSeconds);
//     const ppgData = [];
    
//     // 模拟心率逐渐增加（从80bpm到100bpm），表示疲劳增加
//     for (let i = 0; i < samples; i++) {
//         const t = i / sampleRate;
//         // 主频率（心率）：从1.33Hz (80bpm) 到1.67Hz (100bpm)
//         const heartRateFreq = 1.33 + (1.67 - 1.33) * (i / samples);
//         // PPG波形：主正弦波 + 次谐波 + 噪声 + 基线漂移
//         const mainWave = Math.sin(2 * Math.PI * heartRateFreq * t);
//         const harmonic = 0.3 * Math.sin(2 * Math.PI * 2 * heartRateFreq * t);
//         const noise = (Math.random() - 0.5) * 0.1;
//         const baselineDrift = 0.2 * Math.sin(2 * Math.PI * 0.05 * t); // 低频漂移
//         const ppgSample = mainWave + harmonic + noise + baselineDrift;
//         ppgData.push(ppgSample);
//     }
    
//     return ppgData;
// }

// // 模拟实时处理并计算疲劳度
// function simulateFatigueDetection() {
//     const sampleRate = 250; // 250Hz
//     const duration = 30; // 模拟30秒
//     const detector = new PPGFatigueDetector(sampleRate);
//     const ppgData = generatePPGSignal(sampleRate, duration);
    
//     console.log("Simulating PPG fatigue detection...");
//     for (let i = 0; i < ppgData.length; i++) {
//         const fatigue = detector.processPPG(ppgData[i]);

//                 // 输出
//         console.log(`Data point ${i + 1}:`);
//         console.log(`  PPG: ${ppgData[i]} μV`);
//         console.log(`  Fatigue: ${fatigue}`);
//         console.log('---');

//     }
// }

// // 运行模拟
// simulateFatigueDetection();